package com.demo.demo.controller;

import com.demo.demo.bean.AgriculturalPrice;
import com.demo.demo.bean.QueryInfo;
import com.demo.demo.bean.VarietyTypeResponse;
import com.demo.demo.dao.AgriculturalPriceDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/agricultural")
public class AgriculturalPriceController {

    @Autowired
    private AgriculturalPriceDao agriculturalPriceDao;

    // 获取所有数据（可用于不分页展示）
    @GetMapping("/prices")
    public List<AgriculturalPrice> getAllPrices() {
        return agriculturalPriceDao.findAll();
    }

    // 根据ID获取单个数据
    @GetMapping("/prices/{id}")
    public AgriculturalPrice getPriceById(@PathVariable int id) {
        return agriculturalPriceDao.findById(id);
    }

    // 分页查询农产品价格（支持按产品名搜索）
  @GetMapping("/prices/paged")
public Map<String, Object> getPagedPrices(
        @RequestParam(defaultValue = "") String product,
        @RequestParam(required = false) String varietyType,
        @RequestParam(defaultValue = "1") int pageNum,
        @RequestParam(defaultValue = "10") int pageSize,
        @RequestParam(required = false) String sortBy,
        @RequestParam(defaultValue = "asc") String order) {

    if (sortBy == null || sortBy.isEmpty()) {
        sortBy = "highestPrice";
    }

    if (!List.of("highestPrice", "lowestPrice", "bulkPrice", "quantity").contains(sortBy)) {
        throw new IllegalArgumentException("Invalid sort field: " + sortBy);
    }

    if (!order.equalsIgnoreCase("asc") && !order.equalsIgnoreCase("desc")) {
        throw new IllegalArgumentException("Order must be 'asc' or 'desc'");
    }

    QueryInfo query = new QueryInfo();
    query.setProduct(product);
    query.setVarietyType(varietyType); // ✅ 设置新字段
    query.setSortBy(sortBy);
    query.setOrder(order);
    query.setPageStart((pageNum - 1) * pageSize);
    query.setPageSize(pageSize);

    List<AgriculturalPrice> prices = agriculturalPriceDao.findPaged(query);
    int total = agriculturalPriceDao.getTotalCount(product);

    Map<String, Object> result = new HashMap<>();
    result.put("total", total);
    result.put("data", prices);
    return result;
}

    @DeleteMapping("/prices/delete-zero-quantity")
    public ResponseEntity<Integer> deleteByQuantityZero() {
        int deletedRows = agriculturalPriceDao.deleteByQuantityZero();
        return ResponseEntity.ok(deletedRows);
    }

    //处理商品采购请求（POST）
    @PostMapping("/prices/purchase")
    public Map<String, Object> purchaseProduct(@RequestBody Map<String, Object> params) {
        int productId = Integer.parseInt(params.get("productId").toString());
        int purchaseQuantity = Integer.parseInt(params.get("purchaseQuantity").toString());

        // 调用 DAO 方法进行采购和库存更新
        int rowsAffected = agriculturalPriceDao.purchaseAndUpdateStock(productId, purchaseQuantity);

        Map<String, Object> response = new HashMap<>();
        if (rowsAffected > 0) {
            response.put("success", true);
            response.put("message", "采购成功，库存已减少");
        } else {
            response.put("success", false);
            response.put("message", "库存不足或商品不存在");
        }
        return response;
    }
    @GetMapping("/variety-types")
    public List<VarietyTypeResponse> getAllVarietyTypes() {
        return agriculturalPriceDao.findAllVarietyTypes();
    }


}
